//
//  MKAliyunOSSUtils.m
//  Fanmugua
//
//  Created by xiaomk on 2020/2/13.
//  Copyright © 2020 taolang. All rights reserved.
//

#import "MKAliyunOSSUtils.h"
#import "HYAliOSSModel.h"
#import <AliyunOSSiOS/AliyunOSSiOS.h>

#define MK_IMPL_SHAREDINSTANCE(type)\
static type *sharedInstance = nil;\
+ (instancetype)sharedInstance {\
    static dispatch_once_t once;\
    dispatch_once(&once, ^{\
        sharedInstance = [[self alloc] init];\
    });\
    return sharedInstance;\
}\
+ (instancetype)allocWithZone:(struct _NSZone *)zone{\
    static dispatch_once_t once;\
    dispatch_once(&once, ^{\
        sharedInstance = [super allocWithZone:zone];\
    });\
    return sharedInstance;\
}

@interface MKAliyunOSSUtils ()
@property (nonatomic, strong) OSSClient *client;
@end

//static NSString * const OSS_STS_URL     = @"5c6a711af1f556b88500023f";
//#ifdef APP_HUAYA
static NSString * const OSS_endPoint        = @"https://oss-us-west-1.aliyuncs.com";
static NSString * const kHY_app_image_host  = @"img.taintale.com";
//static NSString * const kHY_app_image_host  = @"img.huaya.run";
static NSString * const OSS_bucketName      = @"tain-tale-oss";
//#else
//static NSString * const OSS_endPoint        = @"https://oss-cn-shanghai.aliyuncs.com";
//static NSString * const kHY_app_image_host  = @"img.fanmugua.net";
//static NSString * const OSS_bucketName      = @"cgnovel";
//static NSString * const kHY_app_image_host  = @"img.mhkjf.com";
//#endif

//static NSString * const OSS_bucketName  = @"yaahao";

@implementation MKAliyunOSSUtils
MK_IMPL_SHAREDINSTANCE(MKAliyunOSSUtils);
//- (id)init{
//    if (self = [super init]) {
////        id<OSSCredentialProvider> credential = [[OSSAuthCredentialProvider alloc] initWithAuthServerUrl:OSS_STS_URL];
////        self.client = [[OSSClient alloc] initWithEndpoint:OSS_endPoint credentialProvider:credential];
//    }
//    return self;
//}

- (void)uploadImage:(UIImage *)image block:(void (^)(NSString *url))block{
    [self uploadImage:image type:CGUploadImageType_avatar block:block];
}

- (void)uploadImage:(UIImage *)image type:(CGUploadImageType)type block:(void (^)(NSString *url))block{
    MJWeakSelf
    
    [APIManager sendGetRequest:[APIURLManager getAliYunOSSConfig] parameters:@{} model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
        if (success) {
            HYAliOSSModel *model = [HYAliOSSModel mj_objectWithKeyValues:requestModel.data];
            OSSClientConfiguration *cfg = [[OSSClientConfiguration alloc] init];
            cfg.maxRetryCount = 3;
            cfg.timeoutIntervalForRequest = 15;
            cfg.isHttpdnsEnable = NO;
            cfg.crc64Verifiable = YES;

            id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc]
                                                    initWithAccessKeyId:model.accessKeyId
                                                    secretKeyId:model.accessKeySecret
                                                    securityToken:model.securityToken];

            weakSelf.client = [[OSSClient alloc] initWithEndpoint:OSS_endPoint
                                               credentialProvider:credential
                                              clientConfiguration:cfg];
            NSString *path = @"";
            if (type == CGUploadImageType_avatar) {
                path = @"Images/IOS/Face/";
            }else if(type == CGUploadImageType_cartoon){
                path = @"Images/IOS/Novel/";
            }else{
                path = @"Images/IOS/feedback/";
            }
            NSString *objectKey = [NSString stringWithFormat:@"%@face%@.jpg",path,@([[[NSDate alloc] init] timeIntervalSince1970]*1000)];
            OSSPutObjectRequest *put = [OSSPutObjectRequest new];
            put.bucketName = OSS_bucketName;
            put.objectKey = objectKey;
            //            put.uploadingData = UIImageJPEGRepresentation(image, 1.0); // 直接上传NSData
            put.uploadingData = [self getRatio:image];
            put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
                NSLog(@"sent:%@, tatal: %@, %%%0.4f", @(totalByteSent), @(totalBytesExpectedToSend), totalByteSent*100.0/totalBytesExpectedToSend);
            };
            OSSTask *putTask = [weakSelf.client putObject:put];
            [putTask continueWithBlock:^id(OSSTask *task) {
                task = [weakSelf.client presignPublicURLWithBucketName:OSS_bucketName withObjectKey:objectKey];
                if (!task.error && [task.result isKindOfClass:[NSString class]]) {
                    NSString *url = task.result;
                    NSString *tStr = [NSString stringWithFormat:@"%@%@",OSS_bucketName,@".oss-us-west-1.aliyuncs.com"];
                    url = [url stringByReplacingOccurrencesOfString:tStr withString:kHY_app_image_host];

                    NSLog(@"upload object success! : %@",url);
                    
                    MK_BLOCK_EXEC(block,url)
                } else {
                    NSLog(@"upload object failed, error: %@" , task.error);
                    MK_BLOCK_EXEC(block,nil);
                }
                return nil;
            }];
            //     可以等待任务完成
            [putTask waitUntilFinished];
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        MK_BLOCK_EXEC(block,nil);
    }];
    
//    [CGRequestUtils sendRequestWith:CGReqDataType_configs_getOss block:^(CGResponseInfo * _Nullable response) {
//        HYAliOSSModel *model = [HYAliOSSModel mj_objectWithKeyValues:response.originContent];
//        if (model.status.integerValue == 200) {
//            OSSClientConfiguration *cfg = [[OSSClientConfiguration alloc] init];
//            cfg.maxRetryCount = 3;
//            cfg.timeoutIntervalForRequest = 15;
//            cfg.isHttpdnsEnable = NO;
//            cfg.crc64Verifiable = YES;
////            id<OSSCredentialProvider> credential = [[OSSAuthCredentialProvider alloc] initWithAuthServerUrl:OSS_STS_URL];
////            self.client = [[OSSClient alloc] initWithEndpoint:OSS_endPoint credentialProvider:credential clientConfiguration:cfg];
//
//            id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc]
//                                                    initWithAccessKeyId:model.AccessKeyId
//                                                    secretKeyId:model.AccessKeySecret
//                                                    securityToken:model.Security];
//            
//            weakSelf.client = [[OSSClient alloc] initWithEndpoint:OSS_endPoint
//                                               credentialProvider:credential
//                                              clientConfiguration:cfg];
//            NSString *path = @"";
//            if (type == CGUploadImageType_avatar) {
//                path = @"Images/IOS/Face/";
//            }else if(type == CGUploadImageType_cartoon){
//                path = @"Images/IOS/Novel/";
//            }else{
//                path = @"Images/IOS/feedback/";
//            }
//            NSString *objectKey = [NSString stringWithFormat:@"%@face%@.jpg",path,@([[[NSDate alloc] init] timeIntervalSince1970]*1000)];
//            OSSPutObjectRequest *put = [OSSPutObjectRequest new];
//            put.bucketName = OSS_bucketName;
//            put.objectKey = objectKey;
////            put.uploadingData = UIImageJPEGRepresentation(image, 1.0); // 直接上传NSData
//            put.uploadingData = [self getRatio:image];
//            put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
//                NSLog(@"sent:%@, tatal: %@, %%%0.4f", @(totalByteSent), @(totalBytesExpectedToSend), totalByteSent*100.0/totalBytesExpectedToSend);
//            };
//            OSSTask *putTask = [weakSelf.client putObject:put];
//            [putTask continueWithBlock:^id(OSSTask *task) {
//                task = [weakSelf.client presignPublicURLWithBucketName:OSS_bucketName withObjectKey:objectKey];
//                if (!task.error && [task.result isKindOfClass:[NSString class]]) {
//                    NSString *url = task.result;
////#ifdef APP_HUAYA
//                    NSString *tStr = [NSString stringWithFormat:@"%@%@",OSS_bucketName,@".oss-cn-hangzhou.aliyuncs.com"];
////#else
////                    NSString *tStr = [NSString stringWithFormat:@"%@%@",OSS_bucketName,@".oss-cn-shanghai.aliyuncs.com"];
////#endif
//                    url = [url stringByReplacingOccurrencesOfString:tStr withString:kHY_app_image_host];
//                    
////                    url = [url stringByReplacingOccurrencesOfString:@"cgnovel.oss-cn-shanghai.aliyuncs.com" withString:kHY_app_image_host];
//                    NSLog(@"upload object success! : %@",url);
//                    MK_BLOCK_EXEC(block,url)
//                } else {
//                    NSLog(@"upload object failed, error: %@" , task.error);
//                    MK_BLOCK_EXEC(block,nil);
//                }
//                return nil;
//            }];
//            //     可以等待任务完成
//            [putTask waitUntilFinished];
//        }else{
//            MK_BLOCK_EXEC(block,nil);
//        }
//    }];
}

- (NSData *)getRatio:(UIImage *)image{
    NSData *imgData = UIImageJPEGRepresentation(image, 1.0);
    CGFloat ratio = 1;
    if (imgData.length > 10000000) {
        ratio = 0.2;
    }else if (imgData.length > 5000000){
        ratio = 0.4;
    }else if (imgData.length > 3000000){
        ratio = 0.5;
    }else if (imgData.length > 2000000){
        ratio = 0.6;
    }else if (imgData.length > 1000000){
        ratio = 0.7;
    }
    imgData = UIImageJPEGRepresentation(image, ratio);
    NSLog(@"image data : %@", @(imgData.length));
    return imgData;
}
@end
